"""自定义迭代器2"""


class GraphicIterator:
    """迭代器对象"""

    def __init__(self, list_info):
        self.__list_info = list_info
        self.__index = 0

    def __next__(self):
        """迭代器，返回当前容器迭代的元素"""

        # 3. 判断是否循环完成，进行异常处理
        if self.__index > len(self.__list_info) - 1:
            raise StopIteration
        # 2. 循环迭代
        so = self.__list_info[self.__index]
        self.__index += 1
        return so


class GraphicManager:
    def __init__(self):
        self.__graphics = []

    def add_graphics(self, graphics):
        self.__graphics.append(graphics)

    def __iter__(self):
        # 1. 创建迭代器
        return GraphicIterator(self.__graphics)



class Graphic:
    # def calculate(self):
    #     raise NotImplementedError()
    def __init__(self, name, age):
        self.name = name
        self.age = age


if __name__ == "__main__":
    zs = GraphicManager()
    zs.add_graphics(Graphic("张三", 22))
    zs.add_graphics(Graphic("李四", 23))
    zs.add_graphics(Graphic("王五", 24))
    man = zs.__iter__()
    while True:
        try:
            lp = man.__next__()
            print(lp.name, lp.age)
        # 5.这里接收并处理异常
        except StopIteration:
            break

    # 上面与下面代码等同无异
    for i in zs:
        print(i.name)